package com.tek.ding.faceding.network.rx;

import android.content.Context;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.tek.ding.faceding.R;
import com.tek.ding.faceding.network.exception.ApiException;
import com.tek.ding.faceding.network.exception.BaseException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

public class RxErrorHandles {

    private Context context;

    public RxErrorHandles(Context context) {
        this.context = context;
    }

    public BaseException handleError(Throwable e) {
        BaseException baseException = new BaseException();

        int status = 0;
        String msg = "";
        if (e instanceof ApiException) {
            ApiException apiException = (ApiException) e;
            baseException.setStatus(apiException.getStatus());
            msg = apiException.getMessage();
        } else if (e instanceof ConnectException) {
            status = BaseException.CONNECT_ERROR;
            msg = context.getResources().getString(R.string.error_connect);
        } else if (e instanceof SocketException) {
            status = BaseException.SOCKET_ERROR;
            msg = context.getResources().getString(R.string.error_socket);
        } else if (e instanceof SocketTimeoutException) {
            status = BaseException.SOCKET_TIMEOUT_ERROR;
            msg = context.getResources().getString(R.string.error_socket_timeout);
        } else if (e instanceof HttpException) {
            status = BaseException.HTTP_ERROR;
            msg = context.getResources().getString(R.string.error_http);
        } else if (e instanceof NullPointerException) {
            status = BaseException.NULL_ERROR;
            msg = context.getResources().getString(R.string.error_null);
        } else if (e instanceof JsonSyntaxException) {
            status = BaseException.JSON_ERROR;
            msg = context.getResources().getString(R.string.error_json);
        } else if (e instanceof UnknownHostException) {
            status = BaseException.NETWORK_ERROR;
            msg = context.getResources().getString(R.string.error_network);
        } else {
            status = BaseException.UNKNOWN_ERROR;
            msg = context.getResources().getString(R.string.error_unknown);
        }

        baseException.setStatus(status);
        baseException.setMessage(msg);
        return baseException;
    }

    public void showErrorMsg(BaseException e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
